package com.vgooo.client.tool.tester;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.vgooo.client.R;
import com.vgooo.util.UmengUtils;
import com.vgooo.util.Utils;

public class TestAudio extends BaseTestActivity {

	final static String KEY = "audio";

	public MediaPlayer mediaPlayerRece;

	public MediaPlayer mediaPlayerReco;

	private File myRecAudioFile;
	private File myRecAudioDir;
	private File myPlayFile;
	private MediaRecorder mMediaRecorder01;

	public Button recordButton;
	public Button receiverButton;
	public Button playButton;
	public ArrayList<String> recordFiles;

	public boolean isStopRecorde = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.test_audio);
		init(KEY);

		AudioManager audioMa = (AudioManager) this
				.getSystemService(Context.AUDIO_SERVICE);
		audioMa.setStreamVolume(AudioManager.STREAM_MUSIC,
				audioMa.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);

		receiverButton = (Button) findViewById(R.id.test_receiver);

		mediaPlayerRece = MediaPlayer.create(this, R.raw.sound);

		receiverButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				AudioManager m_amAudioManager;

				m_amAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

				m_amAudioManager.setSpeakerphoneOn(true);

				m_amAudioManager.setMode(AudioManager.MODE_IN_CALL);

				// 開始放音樂
				mediaPlayerRece.start();

				// 最後再把它設定從Speaker放音，達成！

				m_amAudioManager.setMode(AudioManager.MODE_NORMAL);
			}
		});

		if (Utils.isSDCardAvable()) {
			myRecAudioDir = Environment.getExternalStorageDirectory();
		}

		// getRecordFiles();

		playButton = (Button) findViewById(R.id.play);
		recordButton = (Button) findViewById(R.id.record);
		recordButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				try {
					if (isStopRecorde) {

						if (!Utils.isSDCardAvable()) {
							Toast.makeText(TestAudio.this, "请插入SD CARD",
									Toast.LENGTH_SHORT).show();
							return;
						}
						myRecAudioFile = File.createTempFile("testAudio",
								".amr", myRecAudioDir);

						mMediaRecorder01 = new MediaRecorder();
						mMediaRecorder01
								.setAudioSource(MediaRecorder.AudioSource.MIC);
						mMediaRecorder01
								.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
						mMediaRecorder01
								.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
						mMediaRecorder01.setOutputFile(myRecAudioFile
								.getAbsolutePath());
						mMediaRecorder01.prepare();
						mMediaRecorder01.start();

						recordButton.setText((String) getResources().getText(
								R.string.but_test_stop_record));
						playButton.setEnabled(false);

						isStopRecorde = false;
					} else {

						if (myRecAudioFile != null) {

							mMediaRecorder01.stop();
							mMediaRecorder01.release();
							mMediaRecorder01 = null;

							recordButton.setText((String) getResources()
									.getText(R.string.but_test_record));

							myPlayFile = myRecAudioFile;
						}
						playButton.setEnabled(true);
						isStopRecorde = true;
					}

				} catch (IllegalStateException e) {
					UmengUtils.onError(TestAudio.this, e.toString());
					throw new RuntimeException(e.getMessage());
				} catch (IOException e) {
					UmengUtils.onError(TestAudio.this, e.toString());
					throw new RuntimeException(e.getMessage());
				}
			}
		});
		playButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (myPlayFile != null && myPlayFile.exists()) {
					openFile(myPlayFile);
				}
			}
		});
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		// 友盟统计功能，打开页面
		MobclickAgent.onResume(this);
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		// 友盟统计功能，页面关闭
		MobclickAgent.onPause(this);
		super.onPause();
	}

	public RadioButton rec_int;
	public RadioButton rec_hst;

	private void openFile(File f) {
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_DEFAULT);

		String type = getMIMEType(f);
		intent.setDataAndType(Uri.fromFile(f), type);
		startActivity(intent);
	}

	private String getMIMEType(File f) {
		String end = f
				.getName()
				.substring(f.getName().lastIndexOf(".") + 1,
						f.getName().length()).toLowerCase();
		String type = "";
		if (end.equals("mp3") || end.equals("aac") || end.equals("aac")
				|| end.equals("amr") || end.equals("mpeg") || end.equals("mp4")) {
			type = "audio";
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg")) {
			type = "image";
		} else {
			type = "*";
		}
		type += "/*";
		return type;
	}

	private void getRecordFiles() {

		recordFiles = new ArrayList<String>();
		if (Utils.isSDCardAvable()) {
			File files[] = myRecAudioDir.listFiles();
			if (files != null) {
				for (int i = 0; i < files.length; i++) {
					if (files[i].getName().indexOf(".") >= 0) {
						String fileS = files[i].getName().substring(
								files[i].getName().indexOf("."));
						if (fileS.toLowerCase().equals(".amr"))
							recordFiles.add(files[i].getName());
					}
				}
			}
		}

	}
}
